<template>
  <div class="ui-image" :class="{'is-previewable': previewable}">
    <el-image
      class="ui-image__control"
      v-bind="$props"
      v-on="$listeners"
      :src="innerSrc"
      :style="style"
      :preview-src-list="previewList"
    />
    <div class="ui-image__mask" v-if="previewable"></div>
  </div>
</template>
<script>
import Image from 'element-ui/lib/image'
import 'element-ui/lib/theme-chalk/image.css'

/**
 * 格式化图片地址
*/
function formatImageSrc(src) {
  if (!src) {
    return
  }
  if (src.indexOf('blob:') === 0 || src.indexOf('data:') === 0 || src.indexOf('/') === 0) {
    return src
  }
  if (!(/^(http|https)/i.test(src)) && src.indexOf('//') !== 0) {
    return '//' + src
  }
  return src
}

export default {
  name: 'UiImage',
  components: {
    ElImage: Image
  },
  props: Object.assign({}, Image.props, {
    width: {
      type: String,
      default: ''
    },
    height: {
      type: String,
      default: ''
    },
    previewable: {
      type: Boolean,
      default: false
    }
  }),
  computed: {
    style() {
      const sy = {}
      if (this.width) {
        sy.width = this.width
      }
      if (this.height) {
        sy.height = this.height
      }
      return sy
    },
    innerSrc() {
      return formatImageSrc(this.src)
    },
    previewList() {
      if (!this.previewable || !this.innerSrc) {
        return
      }
      return [this.innerSrc]
    }
  }
}
</script>
<style lang="less">
.ui-image {
  display: inline-block;
  position: relative;
  &.is-previewable {
    &:hover {
      .ui-image__mask{
        opacity: 1;
      }
    }
  }
}
.ui-image__mask{
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  transition: all .25s;
  z-index: 3;
  opacity: 0;
  transform: all .25s;
  background-color: rgba(0,0,0,.6);
  pointer-events: none;
  &:after {
    content: '';
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    transition: all .25s;
    z-index: 3;
    background-image: url('./zoom-in-line.svg');
    background-repeat: no-repeat;
    background-position: 50% 50%;
    background-size: 36px;
    opacity: .9;
  }
}
.ui-image__control{
  display: inline-block;
  vertical-align: top;
}
</style>
